package com.atguigu.gmall.order.listener;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.config.mq.MqService;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.order.biz.OrderBizService;
import com.atguigu.gmall.order.entity.OrderInfo;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@Slf4j
public class MqListener {
    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    MqService mqService;

    @Autowired
    OrderBizService orderBizService;

    /*@RabbitListener(queues = "haha")//设置监听的队列
    public void listen1(Message message, Channel channel) throws IOException {
        String string = new String(message.getBody());
        System.out.println("收到消息:"+string+";  正在处理。。。");

        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        try {
            // 执行的动作

            // 消息执行成功，删除
            // 消息标签，是否批量处理
            channel.basicAck(deliveryTag,false);
        } catch (Exception e) {
            //消息执行失败不删除
            channel.basicNack(deliveryTag,false,false);
            throw new RuntimeException(e);
        }
    }*/

    @RabbitListener(queues = MqConst.ORDER_DEAD_QUEUE)
    public void listen(Message message,Channel channel) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        String content = new String(message.getBody());
        OrderInfo orderInfo = JSON.parseObject(content, OrderInfo.class);

        //进行关单。
        //消息重复。
        try {
            boolean order = orderBizService.closeOrder(orderInfo.getId(), orderInfo.getUserId());
            if (order){
                channel.basicAck(deliveryTag,false);
            }else {
                channel.basicNack(deliveryTag,false,false);
            }
        } catch (Exception e) {
            //1. 只要消息的MD5相同就是同一个消息
            mqService.retry(channel, deliveryTag, content,5);

            //可能会导致无限的消费入队，cpu打满
            throw new RuntimeException(e);
        }

        log.info("收到需要关单的消息:{}",content);
    }


}
